#include <Metro.h>
#include <pfodParser.h>

const byte SensPin = 7;
const byte PWMPin = 3;


byte PWMValue = 0;
pfodParser parser;
Metro timerUpdateSense(100);
Metro timerUpdatePWMValue(500);

void getMainMenu(boolean update=false);

void setup() {
  Serial.begin(9600);

  pinMode(SensPin, OUTPUT);
  pinMode(PWMPin, OUTPUT);

  loadConfig;
  updateSensor();
  setupSensor();
  analogWrite(PWMPin, PWMValue);
}

void loop() {
  if (Serial.available() > 0) {
    byte in = 0;  
    in = Serial.read();
    byte cmd = parser.parse(in);
    if (cmd != 0) { 
      boolean update = false;
              
      if (cmd == 'p') {
        if(parser.getArgsCount()>0){
          byte* idxPtr = parser.getFirstArg();
          long longResult;
          parser.parseLong(idxPtr,&longResult);
          longResult = map(longResult,-2147483648,2147483647,0,255);
          PWMValue = byte(longResult);
          update = true;
        } 
      }
      
      if (cmd == 's') {
        MenuUpdateSensVal();
        update = true;
      }
      
      getMainMenu(update);
    }
  }

  //Update Sensor
  if (timerUpdateSense.check()){
    updateSensor();
  }
  
  //write PWM Value
  if (timerUpdatePWMValue.check()){
    analogWrite(PWMPin, PWMValue);
  }
  delay(2);
}

void getMainMenu(boolean update) {
  String MenuStr;
  if (!update)
    MenuStr="{."; // start a pfod Menu msg
  else
    MenuStr="{:"; // update screen

  MenuStr +="TSW LED-Control...\n...and there'll be light"; // title of this menu
  MenuStr +="`1000"; //Update menu interval
  MenuStr +="|s~Sensor (";
  MenuStr +=String(aktSensVal());
  MenuStr += ")";            
  MenuStr +="|PWMValue`500|p~PWMValueSlider`";
  MenuStr +=String(PWMValue);
  MenuStr +="`255`0 *";
  MenuStr += "}";
  Serial.print(MenuStr);
  Serial.flush();
}

void MenuUpdateSensVal() {
  String MenuStr;
  MenuStr ="{:|s~Sensor (";
  MenuStr +=String(aktSensVal());
  MenuStr += ")}";
  Serial.print(MenuStr);
  Serial.flush();
}





